package cn.liujianbo.example;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * 测试 bloom 过滤器
 *
 * @author 刘建波
 * @date 2021-10-21 22:13
 */
public class BloomFilterTest {
    public static void main(String[] args) {
        // 谷歌布隆过滤器
        BloomFilter<Integer> bf = BloomFilter.create(Funnels.integerFunnel(), 10000, 0.00000000000000001);
        for (int i = 0; i < 10000; i++) {
            bf.put(i);
        }

        int count = 0;
        for (int i = 10000; i < 110000; i++) {
            if (bf.mightContain(i)) {
                count++;
            }
        }
        System.out.println("谷歌bloom filter共误判：" + count + "次！");

        // redis布隆过滤器
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://192.168.56.105:6379");

        RedissonClient redissonClient = Redisson.create(config);
        RBloomFilter<Integer> bloomFilter = redissonClient.getBloomFilter("first");
        bloomFilter.tryInit(10000, 0.03);
        for (int i = 0; i < 10000; i++) {
            bloomFilter.add(i);
        }
        int count2 = 0;
        for (int i = 10000; i < 11000; i++) {
            if (bloomFilter.contains(i)) {
                count2++;
            }
        }
        System.out.println("redis bloom filter 误判：" + count2 + "次");
        redissonClient.shutdown();
    }
}
